package com.hit.server.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hit.server.api.entity.*;
import com.hit.server.api.dto.CheckStrategyQueryDTO;
import com.hit.server.api.dto.CheckStrategySaveDTO;
import com.hit.server.api.dto.CheckStrategyUpdateDTO;
import com.hit.server.api.service.CheckStrategyPositionService;
import com.hit.server.api.vo.CheckStrategyVO;
import com.hit.server.biz.mapper.CheckPositionMapper;
import com.hit.server.biz.mapper.CheckStrategyMapper;
import com.hit.server.api.service.CheckStrategyService;
import com.hit.server.biz.mapper.RobotMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 检测策略
 *
 * @author kehanjiang
 * @date 2025-04-16 11:16:29
 */
@Service
@RequiredArgsConstructor
public class CheckStrategyServiceImpl extends ServiceImpl<CheckStrategyMapper, CheckStrategyEntity> implements CheckStrategyService {
    private final RobotMapper robotMapper;
    private final CheckStrategyPositionService checkStrategyPositionService;
    private final CheckPositionMapper checkPositionMapper;

    private CheckStrategyVO convertToVO(Object o) {
        if (o instanceof CheckStrategyEntity) {
            CheckStrategyVO vo = new CheckStrategyVO();
            BeanUtil.copyProperties(o, vo);
            //设置其他参数
            Optional.ofNullable(vo.getRobotId()).ifPresent(robotId -> {
                RobotEntity robot = robotMapper.selectById(robotId);
                if (robot != null) {
                    vo.setRobotName(robot.getName());
                }
            });

            Long strategyId = vo.getId();
            List<CheckStrategyPositionEntity> refList = checkStrategyPositionService.list(
                    Wrappers.<CheckStrategyPositionEntity>lambdaQuery()
                            .eq(CheckStrategyPositionEntity::getStrategyId, strategyId)
            );
            if (CollUtil.isNotEmpty(refList)) {
                List<CheckPositionEntity> checkPositionEntities = checkPositionMapper.selectList(null);
                Map<Long, String> positionMap = checkPositionEntities.stream().collect(Collectors.toMap(CheckPositionEntity::getId, CheckPositionEntity::getName));
                vo.setPositionIds(refList.stream().map(CheckStrategyPositionEntity::getPositionId).collect(Collectors.toSet()));
                List<String> positionNames = refList.stream()
                        .map(CheckStrategyPositionEntity::getPositionId)
                        .map(id -> positionMap.get(id))
                        .collect(Collectors.toList());
                if (CollUtil.isNotEmpty(positionNames)) {
                    vo.setPositionNames(String.join(",", positionNames));
                }
            }
            return vo;
        }
        return null;
    }

    private void preCheck(CheckStrategyEntity entity, Boolean update) {
        Long id = entity.getId();
        String name = entity.getName();
        if (update) {//更新操作
            Assert.notNull(id, "id不可为空！");
        } else {
            Assert.hasText(name, "name不可为空！");
        }
    }

    @Override
    public Page<CheckStrategyVO> getCheckStrategyPage(Page page, CheckStrategyQueryDTO dto) {
        CheckStrategyEntity entity = new CheckStrategyEntity();
        BeanUtils.copyProperties(dto, entity);
        entity.setName(null);
        final String name = dto.getName();
        LambdaQueryWrapper<CheckStrategyEntity> wrapper = new LambdaQueryWrapper<>(entity);
        wrapper.like(StringUtils.hasText(name), CheckStrategyEntity::getName, name);
        wrapper.orderByAsc(CheckStrategyEntity::getId);
        return (Page<CheckStrategyVO>) this.page(page, wrapper)
                .convert(this::convertToVO);
    }

    @Override
    public CheckStrategyVO getCheckStrategyById(Long id) {
        Assert.notNull(id, "id不可为空！");
        return convertToVO(this.getById(id));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveCheckStrategy(CheckStrategySaveDTO dto) {
        CheckStrategyEntity entity = new CheckStrategyEntity();
        BeanUtils.copyProperties(dto, entity);
        this.preCheck(entity, false);
        //保存检测策略
        this.save(entity);
        //保存点位&策略
        Long strategyId = entity.getId();
        List<Long> checkPositionIds = dto.getPositionIds();
        List<CheckStrategyPositionEntity> saveRefList = new ArrayList<>();
        if (CollUtil.isNotEmpty(checkPositionIds)) {
            for (Long posId : checkPositionIds) {
                saveRefList.add(new CheckStrategyPositionEntity(strategyId, posId));
            }
            checkStrategyPositionService.saveBatch(saveRefList);
        }
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateCheckStrategyById(CheckStrategyUpdateDTO dto) {
        CheckStrategyEntity entity = new CheckStrategyEntity();
        BeanUtils.copyProperties(dto, entity);
        this.preCheck(entity, true);
        Long strategyId = entity.getId();
        //删除点位&策略
        checkStrategyPositionService.remove(Wrappers.<CheckStrategyPositionEntity>lambdaQuery()
                .eq(CheckStrategyPositionEntity::getStrategyId, strategyId));
        //保存点位&策略
        List<Long> checkPositionIds = dto.getPositionIds();
        List<CheckStrategyPositionEntity> saveRefList = new ArrayList<>();
        if (CollUtil.isNotEmpty(checkPositionIds)) {
            for (Long posId : checkPositionIds) {
                saveRefList.add(new CheckStrategyPositionEntity(strategyId, posId));
            }
            checkStrategyPositionService.saveBatch(saveRefList);
        }
        return this.updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeCheckStrategyBatchByIds(List<Long> ids) {
        Assert.notEmpty(ids, "ID不可为空！");
        this.removeBatchByIds(ids);
        return checkStrategyPositionService.remove(Wrappers.<CheckStrategyPositionEntity>lambdaQuery()
                .in(CheckStrategyPositionEntity::getStrategyId, ids));
    }
}